package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import cn.edu.tju.elm.repository.BusinessRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    
    @Autowired
    private CartRepository cartRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private BusinessRepository businessRepository;

    @Override
    @Transactional
    public Cart addCartItem(Cart cart, User currentUser) {
        // 设置购物车项的基本信息
        LocalDateTime now = LocalDateTime.now();
        cart.setCreator(currentUser.getId());
        cart.setCreateTime(now);
        cart.setUpdater(currentUser.getId());
        cart.setUpdateTime(now);
        cart.setDeleted(false);
        cart.setCustomer(currentUser);
        
        // 验证食品信息
        if (cart.getFood() == null || cart.getFood().getId() == null) {
            throw new IllegalArgumentException("食品信息不能为空");
        }
        
        // 获取食品详细信息
        var food = foodRepository.findById(cart.getFood().getId())
                .orElseThrow(() -> new RuntimeException("食品不存在"));
        
        cart.setFood(food);
        
        // 自动推断商家信息（从食品关联的商家）
        if (cart.getBusiness() == null || cart.getBusiness().getId() == null) {
            // 如果请求中没有提供商家信息，从食品关联的商家获取
            if (food.getBusiness() != null) {
                cart.setBusiness(food.getBusiness());
            } else {
                throw new IllegalArgumentException("食品未关联商家，请提供商家信息");
            }
        } else {
            // 如果请求中提供了商家信息，验证商家是否存在
            var business = businessRepository.findById(cart.getBusiness().getId())
                    .orElseThrow(() -> new RuntimeException("商家不存在"));
            cart.setBusiness(business);
            
            // 验证提供的商家是否与食品关联的商家一致
            if (food.getBusiness() != null && !food.getBusiness().getId().equals(business.getId())) {
                throw new IllegalArgumentException("提供的商家与食品关联的商家不一致");
            }
        }
        
        // 设置默认数量（如果未提供）
        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            cart.setQuantity(1);
        }
        
        // 检查是否已存在相同的购物车项
        var existingCart = cartRepository.findByCustomerAndFoodAndBusiness(
            currentUser, food, cart.getBusiness());
        
        if (existingCart.isPresent()) {
            // 如果已存在，则更新数量
            existingCart.get().setQuantity(existingCart.get().getQuantity() + cart.getQuantity());
            existingCart.get().setUpdateTime(now);
            existingCart.get().setUpdater(currentUser.getId());
            return cartRepository.save(existingCart.get());
        } else {
            // 如果不存在，则创建新的购物车项
            return cartRepository.save(cart);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<Cart> getCartItems(User currentUser) {
        return cartRepository.findByCustomer(currentUser);
    }

    @Override
    @Transactional(readOnly = true)
    public Cart getCartItem(Long id, User currentUser) {
        Optional<Cart> cartItemOpt = cartRepository.findByIdAndCustomer(id, currentUser);
        return cartItemOpt.orElse(null);
    }

    @Override
    @Transactional
    public Cart updateCartItem(Long id, Cart cartDetails, User currentUser) {
        Optional<Cart> cartItemOpt = cartRepository.findByIdAndCustomer(id, currentUser);
        if (cartItemOpt.isPresent()) {
            Cart cartItem = cartItemOpt.get();
            
            // 更新数量
            if (cartDetails.getQuantity() != null && cartDetails.getQuantity() > 0) {
                cartItem.setQuantity(cartDetails.getQuantity());
            } else {
                throw new IllegalArgumentException("数量必须大于0");
            }
            
            // 更新时间和更新人
            cartItem.setUpdater(currentUser.getId());
            cartItem.setUpdateTime(LocalDateTime.now());
            
            // 保存更新
            return cartRepository.save(cartItem);
        } else {
            throw new RuntimeException("购物车项不存在或无权修改");
        }
    }

    @Override
    @Transactional
    public void deleteCartItem(Long id, User currentUser) {
        try {
            // 先检查购物车项是否存在且属于当前用户
            if (!cartRepository.existsByIdAndCustomer(id, currentUser)) {
                throw new RuntimeException("购物车项不存在或无权删除");
            }
            
            // 执行删除操作
            cartRepository.deleteByIdAndCustomer(id, currentUser);
            
            // 验证删除是否成功
            if (cartRepository.existsById(id)) {
                throw new RuntimeException("删除操作未成功执行");
            }
        } catch (Exception e) {
            throw new RuntimeException("删除购物车项失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void clearCart(User currentUser) {
        cartRepository.deleteByCustomer(currentUser);
    }

    @Override
    @Transactional(readOnly = true)
    public CartSummary getCartSummary(User currentUser) {
        // 计算摘要信息
        Integer totalItems = cartRepository.sumQuantityByCustomer(currentUser);
        Double totalAmount = cartRepository.sumAmountByCustomer(currentUser);
        Integer itemCount = cartRepository.countByCustomer(currentUser);
        
        // 处理可能的空值
        totalItems = totalItems != null ? totalItems : 0;
        totalAmount = totalAmount != null ? totalAmount : 0.0;
        itemCount = itemCount != null ? itemCount : 0;
        
        return new CartSummary(totalItems, totalAmount, itemCount);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Cart> getCartItemsByBusinessId(User currentUser, Long businessId) {
        // 1. 根据 businessId 查询商家是否存在
        Business business = businessRepository.findById(businessId)
                .orElseThrow(() -> new RuntimeException("商家不存在"));
        // 2. 调用 Repository 的现有方法进行查询
        return cartRepository.findByCustomerAndBusiness(currentUser, business);
    }
}